#pragma once

/// 封装sock
#include <iostream>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <cstring>
#include <cerrno>

#include "logMessage.hpp"
#include "err.hpp"

static const int defaultfd = -1;
static const int gbacklog = 32;

class Sock
{
public:
    Sock(int fd = defaultfd) : _sock(defaultfd)
    {
    }

    void Socket()
    {
        _sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_sock < 0)
        {
            logMessage(Error, "create socket error id:%d info:%s", errno, strerror(errno));
            exit(SOCKET_ERR);
        }
    }

    void Bind(const uint16_t port)
    {
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;

        if (bind(_sock, (sockaddr *)&local, sizeof(local)) < 0)
        {
            logMessage(Error, "Bind error id:%d info:%s", errno, strerror(errno));
            exit(BIND_ERR);
        }

        logMessage(Info, "Bind success");
    }

    void Listen()
    {
        if (listen(_sock, gbacklog) < 0)
        {
            logMessage(Error, "Listen error id:%d info:%s", errno, strerror(errno));
            exit(LISTEN_ERR);
        }
        logMessage(Info, "Bind success");
    }

    // 将客户端信息存起来
    int Accept(std::string *clientip, uint16_t *clientport)
    {
        sockaddr_in temp;
        socklen_t len = sizeof(temp);
        int sock = accept(_sock, (sockaddr *)&temp, &len);
        if (sock < 0)
        {
            logMessage(Error, "Accept error id:%d info:%s", errno, strerror(errno));
        }
        else
        {
            *clientip = inet_ntoa(temp.sin_addr);
            *clientport = ntohs(temp.sin_port);
        }

        logMessage(Info, "accept success");

        return sock;
    }

    int Connect(const std::string serverip, const uint16_t &serverport)
    {
        sockaddr_in server;
        memset(&server, 0, sizeof(server));

        server.sin_family = AF_INET;
        server.sin_port = htons(serverport);
        server.sin_addr.s_addr = inet_addr(serverip.c_str());

        return connect(_sock, (sockaddr *)&server, sizeof(server));
    }

    int Fd()
    {
        return _sock;
    }

    void Close()
    {
        close(_sock);
    }

private:
    int _sock;
};